﻿unit MVC.BaseModel;

interface

uses
  System.SysUtils, System.Classes, mvc.Tool, mvc.json, system.JSON, System.Rtti;

type
  TRemarks = class(TCustomAttribute)
  public
    FText: string;
    FType: string;
    constructor Create(text: string; sDataType: string = '');
  end;

  TBaseModel = class
  public
    function toJSONObject: IJObject;
    constructor Create(json: IJObject); overload;
  end;

implementation

{ TBaseModel }

constructor TBaseModel.Create(json: IJObject);
var
  _RTTIContext: TRttiContext;
  _type: TRttiType;
  _proper: TRttiField;
  key, stype: string;
  jsonitem: TJSONPair;
begin
  _type := _RTTIContext.GetType(self.ClassType);
  for _proper in _type.GetFields do
  begin
    key := _proper.Name;
    stype := _proper.FieldType.ToString;
    jsonitem := json.O.Get(key);
    if jsonitem <> nil then
    begin
      _proper.SetValue(self, jsonitem.JsonValue.Value);
    end;
  end;
end;

function TBaseModel.toJSONObject: IJObject;
var
  _RTTIContext: TRttiContext;
  _type: TRttiType;
  _proper: TRttiField;
  json: string;
  key, value,stype: string;
  _value: TValue;
begin
  _type := _RTTIContext.GetType(self.ClassType);
  json := '';

  for _proper in _type.GetFields do
  begin
    key := '"' + (_proper.Name) + '"';
    stype := _proper.FieldType.ToString;
    _value := _proper.GetValue(self);
    value := _value.AsVariant;
    if Pos('string', stype) > 0 then
      value := '"' + (value) + '"';
    json := json + key + ':' + value + ',';
  end;
  json := json.Substring(0, json.Length - 1);
  if json <> '' then
    json := '{' + json + '}'
  else
    json := '{}';
  Result := IIJObject(json);
end;

{ TRemarks }

constructor TRemarks.Create(text, sDataType: string);
begin
  self.FText := text;
  self.FType := sDataType;
end;

end.

